package com.jstyle.jclifexd.activity;

import android.Manifest;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.daoManager.UserInfoDaoManager;
import com.jstyle.jclifexd.model.Createdmode;
import com.jstyle.jclifexd.model.NetResultData;
import com.jstyle.jclifexd.utils.CoordinateUtil;
import com.jstyle.jclifexd.utils.DateUtil;
import com.jstyle.jclifexd.utils.ImgUtil;
import com.jstyle.jclifexd.utils.NetWorkConast;
import com.jstyle.jclifexd.utils.ScreenUtils;
import com.jstyle.jclifexd.utils.StatusBarUtil;
import com.jstyle.jclifexd.utils.Utils;
import com.jstyle.jclifexd.view.BottomDialog;
import com.yalantis.ucrop.UCrop;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 创建活动 1
 */
public class CreateActivitiesoneActivity extends BaseActivity {
    @BindView(R.id.poster_img)
    ImageView poster_img;
    @BindView(R.id.info_poster)
    TextView info_poster;
    @BindView(R.id.team_name)
    EditText team_name;
    @BindView(R.id.starttime_value)
    Button starttime_value;
    @BindView(R.id.endtime_value)
    Button endtime_value;
    @BindView(R.id.over_value)
    Button over_value;
    @BindView(R.id.area_value)
    Button area_value;
    @BindView(R.id.typr_value)
    Button typr_value;


    BottomDialog sportdailog, chosepic, starttime;
    Createdmode createdmode;
    AMapLocation aMapLocation = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题栏
        setContentView(R.layout.activity_creteone);
        StatusBarUtil.setRootViewFitsSystemWindows(this,true);
        StatusBarUtil.setTranslucentStatus(this);
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            StatusBarUtil.setStatusBarColor(this,0x55000000);
        }
        ButterKnife.bind(this);
        sportdailog = new BottomDialog(CreateActivitiesoneActivity.this, R.layout.dialog_spotype);
        chosepic = new BottomDialog(CreateActivitiesoneActivity.this, R.layout.dialog_chosepic);
        starttime = new BottomDialog(CreateActivitiesoneActivity.this, R.layout.dialog_starttime);
        createdmode = new Createdmode();
        final AMapLocationClient aMapLocationClient = new AMapLocationClient(this);
        aMapLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocationb) {
                if (aMapLocationb.getErrorCode() == 0) {
                    aMapLocation = aMapLocationb;
                    aMapLocationClient.stopLocation();
                }
            }
        });
        aMapLocationClient.startLocation();
    }


    @OnClick({R.id.iv_back, R.id.create_nextstep, R.id.poster_img,
            R.id.typr_value, R.id.starttime_value, R.id.endtime_value
            , R.id.over_value, R.id.area_value})
    public void onViewClicked(View view) {
        if (Utils.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.poster_img://拍照或者相册弹出
                if (chosepic.isshoeww()) {
                    chosepic.dismiss();
                } else {
                    chosepic.show();
                    chosepic.setWithandHeight(CreateActivitiesoneActivity.this, ScreenUtils.dip2px(this, 250));
                    getviewByphotograph();
                }
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.create_nextstep:
                if (TextUtils.isEmpty(createdmode.getImgUrl())) {
                    showToast(getResources().getString(R.string.campaign_poster));
                    return;
                }
                createdmode.setTitle(team_name.getText().toString());
                if (TextUtils.isEmpty(createdmode.getTitle())) {
                    showToast(getResources().getString(R.string.activity_name));
                    return;
                }
                if (TextUtils.isEmpty(createdmode.getSportType())) {
                    showToast(getResources().getString(R.string.select_type));
                    return;
                }
                if (TextUtils.isEmpty(createdmode.getStart())) {
                    showToast(getResources().getString(R.string.select_starttime));
                    return;
                }
                if (TextUtils.isEmpty(createdmode.getEnd())) {
                    showToast(getResources().getString(R.string.select_endtime));
                    return;
                }
                if (TextUtils.isEmpty(createdmode.getSignupTime())) {
                    showToast(getResources().getString(R.string.select_registration));
                    return;
                }

                if (TextUtils.isEmpty(createdmode.getAddress())) {
                    showToast(getResources().getString(R.string.choice_location));
                    return;
                }

                Intent intentt = new Intent(this, CreateActivitiestwoActivity.class);
                intentt.putExtra("createdmode", createdmode);
                startActivity(intentt);
                finish();
                break;
            case R.id.typr_value://类型选择
                if (sportdailog.isshoeww()) {
                    sportdailog.dismiss();
                } else {
                    sportdailog.show();
                    sportdailog.setWithandHeight(CreateActivitiesoneActivity.this, ScreenUtils.dip2px(this, 300));
                    getviewByptype();
                }
                break;

            case R.id.starttime_value://开始时间
                ShoewTimeDialog();
                getviewstartTime(0);
                break;
            case R.id.endtime_value://结束时间
                ShoewTimeDialog();
                getviewstartTime(1);
                break;
            case R.id.over_value://结束时间
                if (TextUtils.isEmpty(createdmode.getStart())) {
                    showToast(getResources().getString(R.string.select_starttime));
                    return;
                }
                if (TextUtils.isEmpty(createdmode.getEnd())) {
                    showToast(getResources().getString(R.string.select_endtime));
                    return;
                }
                ShoewTimeDialog();
                getviewstartTime(2);
                break;

            case R.id.area_value:
                if (null != aMapLocation) {
                    Log.e("adad", aMapLocation.getLatitude() + "*******" + aMapLocation.getLongitude());
                    if (CoordinateUtil.outOfChina(aMapLocation.getLatitude(), aMapLocation.getLongitude())) {//google
                        startGoogle();
                    } else {
                        LatLng myLatLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                        if (Utils.isTAiwan(myLatLng) || Utils.isXianggan(myLatLng)) {//香港、或者台湾//google
                            startGoogle();
                        } else {
                            Intent intent = new Intent(CreateActivitiesoneActivity.this, GaodeSeachAtivity.class);
                            startActivityForResult(intent, 6543);
                        }
                    }
                } else {
                    showToast(getResources().getString(R.string.position_acquisition));
                }
                break;
        }
    }


    private void startGoogle() {
        Intent intent = new Intent(CreateActivitiesoneActivity.this, GoogleSeachAtivity.class);
        intent.putExtra("Latitude", aMapLocation.getLatitude() + "");
        intent.putExtra("Longitude", aMapLocation.getLongitude() + "");
        startActivityForResult(intent, 6543);
    }

    /**
     * 时间选择器
     */
    private void ShoewTimeDialog() {
        if (starttime.isshoeww()) {
            starttime.dismiss();
        } else {
            starttime.show();
            starttime.setWithandHeight(CreateActivitiesoneActivity.this, ScreenUtils.dip2px(this, 420));
        }
    }

    /**
     * 0 开始时间
     * 1结束时间
     * 2 活动截止时间
     *
     * @param type
     */
    String time = "";
    TimePickerDialog timePickerDialog;

    private void getviewstartTime(final int type) {
        time = "";
        final CalendarView secelt_run = starttime.getmView().findViewById(R.id.CalendarView_create);
        final Button bt_data = starttime.getmView().findViewById(R.id.bt_data_month_date);
        final Button statime_submit = starttime.getmView().findViewById(R.id.statime_submit);
        final ImageView left = starttime.getmView().findViewById(R.id.bt_data_month_preMonth);
        final ImageView right = starttime.getmView().findViewById(R.id.bt_data_month_nextMonth);
        left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                secelt_run.scrollToPre();
            }
        });
        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                secelt_run.scrollToNext();
            }
        });
        statime_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                timePickerDialog = new TimePickerDialog(CreateActivitiesoneActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        String times = String.format("%1$02d:%2$02d", hourOfDay, minute);
                        time = time + " " + times + ":" + "00";
                        switch (type) {
                            case 0:
                                if (TextUtils.isEmpty(createdmode.getEnd()) || DateUtil.getTimeExpend(time, createdmode.getEnd())) {
                                    createdmode.setStart(time);
                                    starttime.dismiss();
                                    starttime_value.setText(DateUtil.getCreaetime(CreateActivitiesoneActivity.this, createdmode.getStart()));
                                } else {
                                    time = "";
                                    timePickerDialog.cancel();
                                    starttime.dismiss();
                                    showToast(getString(R.string.star_timeerror));
                                }
                                break;
                            case 1:
                                if (TextUtils.isEmpty(createdmode.getStart()) || DateUtil.getTimeExpend(createdmode.getStart(), time)) {
                                    createdmode.setEnd(time);
                                    starttime.dismiss();
                                    endtime_value.setText(DateUtil.getCreaetime(CreateActivitiesoneActivity.this, createdmode.getEnd()));
                                } else {
                                    time = "";
                                    timePickerDialog.cancel();
                                    starttime.dismiss();
                                    showToast(getString(R.string.end_timeerror));
                                }
                                break;
                            case 2:
                                if (DateUtil.getInTime(createdmode.getStart(), createdmode.getEnd(), time)) {
                                    createdmode.setSignupTime(time);
                                    starttime.dismiss();
                                    over_value.setText(DateUtil.getCreaetime(CreateActivitiesoneActivity.this, createdmode.getSignupTime()));
                                } else {
                                    time = "";
                                    timePickerDialog.cancel();
                                    starttime.dismiss();
                                    showToast(getString(R.string.deadline));
                                }
                                break;

                        }
                    }
                }, Integer.valueOf(DateUtil.getHour()), Integer.valueOf(DateUtil.getMintes()), true);
                timePickerDialog.show();
                ScreenUtils.setButtonTextColor(timePickerDialog);
            }
        });
        secelt_run.setOnMonthChangeListener(new CalendarView.OnMonthChangeListener() {
            @Override
            public void onMonthChange(int year, int month) {
                if (Utils.isZh(CreateActivitiesoneActivity.this)) {
                    bt_data.setText(year + getResources().getString(R.string.Yearly) + String.format("%02d", month) + getResources().getString(R.string.Monthly) + String.format("%02d", 1) + getResources().getString(R.string.Daily));
                } else {
                    bt_data.setText(String.format("%02d", month) + "/" + String.format("%02d", 1) + "/" + year);
                }
                time = year + "-" + String.format("%02d", month) + "-" + String.format("%02d", 1);
            }
        });
        secelt_run.setOnDateSelectedListener(new CalendarView.OnDateSelectedListener() {
            @Override
            public void onDateSelected(Calendar calendar, boolean isClick) {
                if (Utils.isZh(CreateActivitiesoneActivity.this)) {
                    bt_data.setText(calendar.getYear() +  getResources().getString(R.string.Yearly) + String.format("%02d", calendar.getMonth()) + getResources().getString(R.string.Monthly) + String.format("%02d", calendar.getDay()) + getResources().getString(R.string.Daily));
                } else {
                    bt_data.setText(String.format("%02d", calendar.getMonth()) + "/" + String.format("%02d", calendar.getDay()) + "/" + calendar.getYear());
                }
                time = calendar.getYear() + "-" + String.format("%02d", calendar.getMonth()) + "-" + String.format("%02d", calendar.getDay());
            }
        });

    }


    private void getviewByptype() {
        final ImageView secelt_run = sportdailog.getmView().findViewById(R.id.secelt_run);
        final ImageView secelt_riding = sportdailog.getmView().findViewById(R.id.secelt_riding);
        secelt_run.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//跑步
                createdmode.setSportType("running");
                secelt_run.setImageDrawable(getResources().getDrawable(R.drawable.running_check));
                secelt_riding.setImageDrawable(getResources().getDrawable(R.drawable.cycling_uncheck));

            }
        });
        secelt_riding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//骑行
                createdmode.setSportType("cycling");
                secelt_run.setImageDrawable(getResources().getDrawable(R.drawable.running_uncheck));
                secelt_riding.setImageDrawable(getResources().getDrawable(R.drawable.cycling_check));
            }
        });
        sportdailog.getmView().findViewById(R.id.spotype_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//取消
                if (!TextUtils.isEmpty(createdmode.getSportType()) && null != sportdailog) {
                    sportdailog.dismiss();
                    if (createdmode.getSportType().equals("running")) {
                        typr_value.setText(getResources().getString(R.string.run));
                    } else {
                        typr_value.setText(getResources().getString(R.string.riding));
                    }
                } else {
                    showToast(getResources().getString(R.string.select_type));
                }
            }
        });
    }


    private void getviewByphotograph() {
        chosepic.getmView().findViewById(R.id.photograph).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//拍照
                photograph();
                chosepic.dismiss();
            }
        });
        chosepic.getmView().findViewById(R.id.album).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//打开相册
                openAlbum();
                chosepic.dismiss();
            }
        });
        chosepic.getmView().findViewById(R.id.chosepic_cance).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//取消
                if (null != chosepic) {
                    chosepic.dismiss();
                }
            }
        });
    }


    /**
     * 拍照
     */
    private void photograph() {
        if (Build.VERSION.SDK_INT >= 23) {//检查相机权限
            ArrayList<String> permissions = new ArrayList<>();
            if (this.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (permissions.size() == 0) {//有权限,跳转
                ImgUtil.openCamera(CreateActivitiesoneActivity.this);
            } else {
                this.requestPermissions(permissions.toArray(new String[permissions.size()]), ImgUtil.REQUEST_CODE_CAMERA);
            }
        } else {
            ImgUtil.openCamera(CreateActivitiesoneActivity.this);
        }
    }

    /**
     * 相册
     */
    private void openAlbum() {
        //如果有权限申请，请在Activity中onRequestPermissionsResult权限返回里面重新调用openAlbum()
        if (ContextCompat.checkSelfPermission(CreateActivitiesoneActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(CreateActivitiesoneActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, ImgUtil.REQUEST_CODE_ALBUM);
        } else {
            ImgUtil.openAlbum(CreateActivitiesoneActivity.this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //正确返回
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ImgUtil.TAKE_PHOTO://相机返回
                    //相机返回图片，调用裁剪的方法
                    ImgUtil.startUCrop(CreateActivitiesoneActivity.this, ImgUtil.imageUri, poster_img.getWidth() * 2, poster_img.getHeight() * 2);
                    break;
                case ImgUtil.CHOOSE_PHOTO://相册返回
                    try {
                        if (data != null) {
                            Uri uri = data.getData();
                            ImgUtil.startUCrop(CreateActivitiesoneActivity.this, uri, poster_img.getWidth() * 2, poster_img.getHeight() * 2);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case UCrop.REQUEST_CROP://剪切返回
                    Uri resultUri = UCrop.getOutput(data);
                    //剪切返回，显示剪切的图片到布局
                    Glide.with(CreateActivitiesoneActivity.this)
                            .load(resultUri)
                            .skipMemoryCache(true)// 不使用内存缓存
                            .diskCacheStrategy(DiskCacheStrategy.NONE) // 不使用磁盘缓存
                            .apply(RequestOptions.bitmapTransform(new RoundedCorners(ScreenUtils.dip2px(CreateActivitiesoneActivity.this, 11f))))
                            .into(poster_img);
                    info_poster.setVisibility(View.GONE);
                    if (NetWorkUtil.isNetworkConnected(CreateActivitiesoneActivity.this)) {
                        //上传图片到服务器
                        String PAHT = ImgUtil.getPath(CreateActivitiesoneActivity.this, resultUri);
                        updateIcon(PAHT);
                    } else {
                        showToast(getString(R.string.Network_not_availa));
                    }
                    break;
            }
        } else if (6543 == resultCode) {
            if (null != data.getStringExtra("date")) {
                area_value.setText(data.getStringExtra("date"));
                createdmode.setAddress(data.getStringExtra("date"));
            }

        }
    }


    private void updateIcon(String path) {
        String uid = UserInfoDaoManager.getUserByUid(NetWorkUtil.getUserId()).getUserId();
        File file = new File(path);
        if (!file.exists()) return;
        Map<String, RequestBody> maps = new HashMap<>();
        RequestBody tokenBody = RequestBody.create(MediaType.parse("text/plain"), uid);
        maps.put(NetWorkConast.KEY_uid, tokenBody);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part muPart = MultipartBody.Part.createFormData("img", file.getName() + ".png", requestBody);
        NetWorkUtil.getInstance().getJstyleApi().uploadPoster(muPart, maps).map(new Function<NetResultData<String>, Object>() {
            @Override
            public Object apply(NetResultData<String> netResultData) throws Exception {
                int msgCode = netResultData.getMsgCode();
                if (msgCode == NetResultData.Success_Code) {
                    Log.e("TAG", netResultData.getData());
                    createdmode.setImgUrl(netResultData.getData());
                }
                return new Object();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Object>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Object value) {
            }

            @Override
            public void onError(Throwable e) {
                Log.e("TAG", "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
            }
        });
    }
}



